<?php

if(isset($_GET['logout'])) {
    session_destroy();
    echo "<h3>You've just logged out!</h3>";
} else {
    $uname = $_POST['uname'];
    $passw = $_POST['passw'];
    //Handle login
    if(isset ($_POST['login'])) {
        $res = mysql_query("SELECT * FROM `user` WHERE `uname` = '$uname' AND `passw` = '$passw'");

        //If user found, logging him in
        if($row = mysql_fetch_row($res)) {
            $_SESSION['uid']    = $row[0];
            $_SESSION['uname']  = $row[1];
        } else {
            echo "<p class='error'>Login failed!</p>";
        }

    //Register
    } else if(isset ($_POST['regis'])) {
        //If user not found, register him
        $res = mysql_query("INSERT INTO user VALUES ('', '$uname', '$passw')");
        $res = mysql_query("SELECT * FROM `user` WHERE `id` = ".mysql_insert_id());
        if($res) {
            $row = mysql_fetch_row($res);
            $_SESSION['uid']    = $row[0];
            $_SESSION['uname']  = $row[1];

            echo "<h3>You've just registered!</h3>";

            //Create a folder dedicated for him
            if(!mkdir("./repo/".$_SESSION['uid']."/",0,true)) {
                die("Failed to create folder!");
            }
        } else {
            echo "<p class='error'>Username taken, please choose another username</p>";
        }
    }

}
?>
<p>You'll be redirected right away!</p>
<script type="text/javascript">
    function redirect() {
        window.location = "index.php";
    }
    setTimeout(redirect, 2000);
</script>